﻿@{ ViewBag.Title = "jqGrid in ASP.NET MVC - CRUD [Inline Editing]"; }

<table id="jqgProducts" cellpadding="0" cellspacing="0"></table>
<div id="jqgpProducts" style="text-align:center;"></div>
<div id="dlgSupplier"></div>

@section JavaScript {
    <script id="tmplSupplier" type="text/x-jquery-tmpl">
        ${CompanyName}<br /><br />
        ${Address}<br />
        ${PostalCode}, ${City}<br />
        ${Country}<br /><br />
        ${Phone}<br />
        ${HomePage}
    </script>
    <script type="text/javascript">
        $.lastSelectedRow = null;

        $(document).ready(function () {
            $('#jqgProducts').jqGrid({
                colNames: ['', 'ProductID', 'ProductName', 'Supplier', 'Category', 'QuantityPerUnit', 'UnitPrice', 'UnitsInStock'],
                colModel: [
                    { formatter: 'actions', formatoptions: { keys: true, delOptions: { beforeSubmit: function(rowId, formId) { $('#products').jqGrid('delRowData', rowId); return [false, 'Selected row has been removed from client array but not from server.'] } } }, resizable: false, search: false, sortable: false, width: 60, viewable: false, name: 'actions' },
                    { name: 'ProductID', index: 'ProductID', align: 'left', editable: false },
                    { name: 'ProductName', index: 'ProductName', align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 40 }, editrules: { required:true } },
                    { name: 'Supplier', index: 'SupplierID', align: 'left', formatter: supplierFormatter, editable: true, edittype: 'select', editoptions: { dataUrl: '@Url.Action("Suppliers")' }, editrules: { required: true} },
                    { name: 'Category', index: 'Category', align: 'left', editable: true, edittype: 'select', editoptions: { dataUrl: '@Url.Action("Categories")' }, editrules: { required: true} },
                    { name: 'QuantityPerUnit', index: 'QuantityPerUnit', align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 20 }, editrules: { required:true } },
                    { name: 'UnitPrice', index: 'UnitPrice', align: 'left', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, prefix: '$'}, editable: true, edittype: 'text', editrules: { required: true, number: true, minValue: 0 } },
                    { name: 'UnitsInStock', index: 'UnitsInStock', align: 'left', formatter: unitsInStockFormatter, unformat: unitsInStockUnFormatter, editable: true, edittype: 'text', editrules: { required: true, integer: true, minValue: 0, maxValue: 32767} }
                ],
                url: '@Url.Action("Products")',
                datatype: 'json',
                editurl: 'clientArray',
                jsonReader: { repeatitems: false, id: 'ProductID' }, 
                loadonce: true,
                mtype: 'POST',
                pager: '#jqgpProducts', 
                rowList: [10,20,30,40,50,100],
                rowNum: 100,
                sortname: 'ProductID',
                viewrecords: true,
                height: '100%'
            })
            .jqGrid('navGrid', '#jqgpProducts', { add: false, edit: false, del: false, search: false })
            .jqGrid('inlineNav', '#jqgpProducts', { edit: false, addParams: { rowID: '_empty' }, editParams: { url: 'clientArray' } });

            $('#dlgSupplier').dialog({ autoOpen: false, bgiframe: true, resizable: false, title: 'Supplier' });
            $('a[data-supplier-id]').live('click', function (e) {
                if (e.preventDefault)
                    e.preventDefault();
                else
                    e.returnValue = false;

                var dialogPosition = $(this).offset();
                $.post('@Url.Action("Supplier")', { supplierId: $(this).attr('data-supplier-id') }, function(data) {
                    $('#dlgSupplier').empty();
                    $('#tmplSupplier').tmpl(data).appendTo('#dlgSupplier');
                    $('#dlgSupplier').dialog('option', 'position', [dialogPosition.left, dialogPosition.top]);
                    $('#dlgSupplier').dialog('open');
                });
            });
        });

        function unitsInStockFormatter(cellvalue, options, rowObject) {
            if (typeof cellvalue != "undefined") {
                var cellValueInt = parseInt(cellvalue);
                if (cellValueInt > 10)
                    return "<img src='@Url.Content("~/Content/images/ui-flag_green.png")' alt='" + cellvalue + "' title='" + cellvalue + "' />";
                else if (cellValueInt > 0)
                    return "<img src='@Url.Content("~/Content/images/ui-flag_blue.png")' alt='" + cellvalue + "' title='" + cellvalue + "' />";
                else
                    return "<img src='@Url.Content("~/Content/images/ui-flag_red.png")' alt='" + cellvalue + "' title='" + cellvalue + "' />";
            } else {
                return cellvalue;
            }
        };

        function unitsInStockUnFormatter(cellvalue, options, cellobject) {
            return $('img', cellobject).attr('title');
        };

        function supplierFormatter(cellvalue, options, rowObject) {
            if (typeof(cellvalue) != 'undefined') {
                if (cellvalue.indexOf('[') == 0) {
                    return cellvalue.substr(cellvalue.indexOf(']') + 2);
                } else {
                    return cellvalue;
                }
            } else {
                return '';
            }
        };
    </script>
}